#!/bin/bash
# 安装 systemd 服务脚本

set -e

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

# 检查是否为 root
if [ "$EUID" -ne 0 ]; then 
    echo -e "${RED}请使用 sudo 运行此脚本${NC}"
    exit 1
fi

# 脚本所在目录
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"

echo -e "${GREEN}=== 安装 AKShare 期权数据定时同步服务 ===${NC}"
echo ""

# 获取当前用户（实际调用 sudo 的用户）
ACTUAL_USER="${SUDO_USER:-$USER}"
ACTUAL_GROUP=$(id -gn "$ACTUAL_USER")

echo "项目路径: $PROJECT_ROOT"
echo "运行用户: $ACTUAL_USER"
echo "运行组: $ACTUAL_GROUP"
echo ""

# 检查二进制文件
BINARY="$PROJECT_ROOT/target/release/akoption-scheduler"
if [ ! -f "$BINARY" ]; then
    echo -e "${YELLOW}未找到编译后的二进制文件，开始编译...${NC}"
    cd "$PROJECT_ROOT"
    sudo -u "$ACTUAL_USER" cargo build --release -p akoption-scheduler
    echo -e "${GREEN}编译完成${NC}"
fi

# 检查配置文件
CONFIG_FILE="$PROJECT_ROOT/config/sync_config.toml"
if [ ! -f "$CONFIG_FILE" ]; then
    echo -e "${RED}错误: 配置文件不存在: $CONFIG_FILE${NC}"
    exit 1
fi

# 创建必要的目录
mkdir -p "$PROJECT_ROOT/data"
mkdir -p "$PROJECT_ROOT/logs"
chown -R "$ACTUAL_USER:$ACTUAL_GROUP" "$PROJECT_ROOT/data"
chown -R "$ACTUAL_USER:$ACTUAL_GROUP" "$PROJECT_ROOT/logs"

# 生成 systemd 服务文件
SERVICE_FILE="/etc/systemd/system/akoption-scheduler.service"
echo -e "${YELLOW}生成 systemd 服务文件...${NC}"

cat > "$SERVICE_FILE" << EOF
[Unit]
Description=AKShare Option Data Scheduler Service
Documentation=https://github.com/akshare/akshare-option-rs
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=$ACTUAL_USER
Group=$ACTUAL_GROUP
WorkingDirectory=$PROJECT_ROOT
ExecStart=$BINARY --config $CONFIG_FILE

# 重启策略
Restart=always
RestartSec=10

# 资源限制
LimitNOFILE=65536
LimitNPROC=4096

# 日志
StandardOutput=journal
StandardError=journal
SyslogIdentifier=akoption-scheduler

# 安全设置
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=$PROJECT_ROOT/data $PROJECT_ROOT/logs

[Install]
WantedBy=multi-user.target
EOF

echo -e "${GREEN}服务文件已创建: $SERVICE_FILE${NC}"

# 重载 systemd
echo -e "${YELLOW}重载 systemd...${NC}"
systemctl daemon-reload

# 启用服务
echo -e "${YELLOW}启用服务...${NC}"
systemctl enable akoption-scheduler

echo ""
echo -e "${GREEN}=== 安装完成 ===${NC}"
echo ""
echo "可用命令:"
echo "  启动服务: sudo systemctl start akoption-scheduler"
echo "  停止服务: sudo systemctl stop akoption-scheduler"
echo "  重启服务: sudo systemctl restart akoption-scheduler"
echo "  查看状态: sudo systemctl status akoption-scheduler"
echo "  查看日志: sudo journalctl -u akoption-scheduler -f"
echo ""
echo -e "${YELLOW}是否现在启动服务? (y/n)${NC}"
read -r response

if [[ "$response" =~ ^[Yy]$ ]]; then
    systemctl start akoption-scheduler
    echo ""
    systemctl status akoption-scheduler
fi
